package com.example.demo.algorithm.linear;

import java.util.Iterator;

/**
 * @Author: xiatian
 * @CreateTime: 2021/9/15 10:13 上午
 * @Description:
 */
public class Stack<T> implements Iterable<T> {
    //记录栈的元素个数
    private int N;
    //记录首节点
    private Node head;


    public Stack() {
        head = new Node(null, null);
        N = 0;
    }


    /**
     * 判断栈是否为空
     *
     * @return
     */
    public boolean isEmpty() {
        return N == 0;
    }

    /**
     * 返回栈的长度
     *
     * @return
     */
    public int length() {
        return N;
    }

    /**
     * 入栈
     *
     * @param t
     */
    public void push(T t) {
        Node oldNode = head.next;
        Node n = new Node(t, oldNode);
        head.next = n;
        //栈的长度加1
        N++;
    }

    /**
     * 弹出栈顶的元素
     *
     * @return
     */
    public T pop() {
        Node oldNode = head.next;
        if (oldNode == null) {
            return null;
        }
        head.next = head.next.next;
        N--;
        return oldNode.item;
    }


    @Override
    public Iterator<T> iterator() {
        return new SIterator();
    }

    private class SIterator implements Iterator<T> {
        private Node n;

        public SIterator() {
            this.n = head;
        }

        @Override
        public boolean hasNext() {
            return n.next != null;
        }

        @Override
        public T next() {
            n = n.next;
            return n.item;
        }
    }


    private class Node {
        T item;
        Node next;

        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }
    }

}
